
Imports System
Imports System.IO
Imports System.Text
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports _2bMatesSite.BO

Namespace _2bMatesSite
	''' <summary>
	''' Summary description for view_awaiting_confirm.
	''' </summary>
	Public Partial Class view_awaiting_confirm
		Inherits BaseWebPage

		Protected litUsersCount As System.Web.UI.WebControls.Literal
		Protected blankImagesCount As Integer = 0
		Protected currentPageNumber As Integer = 0
		Protected firstPageNumber As Integer = 0
		' the first page of page links
		Protected lastPageNumber As Integer = 0
		Protected pagesRest As Integer = 0
		Protected usrID As Integer = -1

		Protected grpID As Integer = -1
		Protected isGroupMode As Boolean = False
		Protected htPageConstants As New Hashtable()

		Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
			' Put user code to initialize the page here

			' this.pageTemplate.PageTitle = PageTitles.VIEW_AWAITING_CONFIRMATION_PAGE;

			' Auto login from an external link
			'AutoLogin( Request );

			Dim usr As User = LoggedUser
			Dim grp As Group = Nothing
			Dim invUsers As UserInvitations = Nothing
			Dim invGroupUsers As GroupsPendingUsers = Nothing
			Dim nWaitingUsersCnt As Double = -1

			If usr = Nothing Then
				Common.Utils.RedirectToLoginPage(Page)
			End If

			Me.initPageTitles(Constants.VIEW_AWAITING_CONFIRMATION, "", _Form1, Nothing, htPageConstants)
			Me.initAdvertisements(_Form1, Nothing)

			' init page title
			litPageTitleUp.Text = Me.GetPageConstText(htPageConstants, "CONST_PageTitle_TEXT")

			' check if a group param is given  
			If Request.Params(Constants.GROUP_PARAM) <> Nothing AndAlso Request.Params(Constants.GROUP_PARAM) <> "" Then
				isGroupMode = True
				Try
					grpID = Convert.ToInt32(Request.Params(Constants.GROUP_PARAM))
				Catch
					Throw New Exception(Constants.ERROR_MESSAGE_MISSING_PARAMETERS)
				End Try

				grp = Groups.GetGroupByID(grpID)
				If grp = Nothing Then
					Throw New Exception(Constants.ERROR_MESSAGE_GROUP_DOESNT_EXIST_ERROR)
				End If

				If grp.Uid <> usr.ID Then
					Throw New Exception(Constants.ERROR_MESSAGE_ONLY_MODERATOR_ACCESS)
				End If
			End If

			If isGroupMode Then
				invGroupUsers = grp.PendingMembers
				nWaitingUsersCnt = invGroupUsers.Count
				hlBackToGroup.NavigateUrl = "../" + Constants.GROUP_WELCOME + "?" + Constants.GROUP_PARAM + "=" + grpID
				hlBackToGroup.Text = (Me.GetPageConstText(htPageConstants, "CONST_GroupBackLink_TEXT")).Replace("[PARAM]", grp.Name)
			Else
				invUsers = usr.PendingInvitations
				nWaitingUsersCnt = invUsers.Count
			End If

			If nWaitingUsersCnt = 0 Then
				lblMessage.Text = Me.GetPageConstText(htPageConstants, "CONST_MsgNoInvites_TEXT")
				lblMessage.Visible = True
				dgPager.Visible = False
				dgPagerUp.Visible = False
			Else
				Dim confParam As String = Request.Params(Constants.CONFIRM_PARAM)
				If confParam <> Nothing AndAlso confParam <> "" Then
					Try
						Select Case Convert.ToInt32(confParam)
							Case Constants.ACCEPT_FRIENDSHIP
								If isGroupMode Then
									lblMessage.Text = (Me.GetPageConstText(htPageConstants, "CONST_MsgConfirmed_TEXT")).Replace("[PARAM]", grp.Name)
								Else
									lblMessage.Text = Me.GetPageConstText(htPageConstants, "CONST_MsgConfirmedUser_TEXT")
								End If
								Exit Select
							Case Constants.REJECT_FRIENDSHIP
								If isGroupMode Then
									lblMessage.Text = (Me.GetPageConstText(htPageConstants, "CONST_MsgReject_TEXT")).Replace("[PARAM]", grp.Name)
								Else
									lblMessage.Text = Me.GetPageConstText(htPageConstants, "CONST_MsgRejectUser_TEXT")
								End If
								Exit Select
						End Select
					Catch
						Throw New Exception(Constants.ERROR_MESSAGE_MISSING_PARAMETERS)
					End Try

					lblMessage.Visible = True
				End If

				If nWaitingUsersCnt = 0 Then
					tblFavUsers.Visible = False
				Else
					dgPager.RedirectPage = Constants.VIEW_AWAITING_CONFIRMATION
					dgPager.MaxPageNumber = Convert.ToInt32(Math.Ceiling(nWaitingUsersCnt / Constants.MAX_PICTURES_ON_AWAITING_PAGE))
					dgPager.Action = ""
					dgPagerUp.RedirectPage = Constants.VIEW_AWAITING_CONFIRMATION
					dgPagerUp.MaxPageNumber = Convert.ToInt32(Math.Ceiling(nWaitingUsersCnt / Constants.MAX_PICTURES_ON_AWAITING_PAGE))
					dgPagerUp.Action = ""

					' initialize listing literals

					dgPager.dgListing.TotalCount = Convert.ToInt32(nWaitingUsersCnt)
					dgPagerUp.dgListing.TotalCount = Convert.ToInt32(nWaitingUsersCnt)

					'initialize current page number
					If Convert.ToInt32(Request.Params("page")) = 0 OrElse dgPager.CurrentPageNumber = 1 Then
						dgPager.CurrentPageNumber = 1
						dgPagerUp.CurrentPageNumber = 1
						ViewState("StartIndex") = 0
					Else
						dgPager.CurrentPageNumber = Convert.ToInt32(Request.Params("page"))
						dgPagerUp.CurrentPageNumber = Convert.ToInt32(Request.Params("page"))
						ViewState("StartIndex") = Convert.ToString(((dgPager.CurrentPageNumber - 1) * Constants.MAX_PICTURES_ON_AWAITING_PAGE))
					End If

					dgPager.PagesRest = dgPager.MaxPageNumber - dgPager.FirstPageNumber + 1
					dgPager.LastPageNumber = Math.Min(dgPager.PagesRest, Constants.MAX_PAGES_NUMS_ON_PAGE)
					dgPagerUp.PagesRest = dgPagerUp.MaxPageNumber - dgPagerUp.FirstPageNumber + 1
					dgPagerUp.LastPageNumber = Math.Min(dgPagerUp.PagesRest, Constants.MAX_PAGES_NUMS_ON_PAGE)

					If Not IsPostBack Then
						BindGrid()
					End If
				End If
			End If
		End Sub

		Protected Function CreateDataSource() As ICollection
			Dim usr As BO.User = Me.LoggedUser
			Dim grp As Group = Groups.GetGroupByID(grpID)
			Dim invUsers As UserInvitations = Nothing
			Dim invGroupUsers As GroupsPendingUsers = Nothing
			Dim nWaitingUsersCnt As Double = -1
			Dim LoggedUsersList As ArrayList = Common.Utils.GetLoggedUsersIDs()

			Dim dt As New DataTable()
			If isGroupMode Then
				invGroupUsers = grp.PendingMembers
				nWaitingUsersCnt = invGroupUsers.Count
			Else
				invUsers = usr.PendingInvitations
				nWaitingUsersCnt = invUsers.Count
			End If

			Dim startIndex As Integer = Convert.ToInt32(ViewState("StartIndex"))
			Dim endIndex As Integer = startIndex + Constants.MAX_PICTURES_ON_AWAITING_PAGE
			Dim t As Integer = 0
			Dim counter As Integer = 0
			Dim pic As UserPicture
			endIndex = Math.Min(endIndex, Convert.ToInt32(nWaitingUsersCnt))
			t = (endIndex - startIndex)
			dgPager.dgListing.StartIndex = startIndex + 1
			dgPager.dgListing.EndIndex = endIndex
			dgPagerUp.dgListing.StartIndex = startIndex + 1
			dgPagerUp.dgListing.EndIndex = endIndex

			Dim dr As DataRow

			dt.Columns.Add(New DataColumn("UserID", GetType(Integer)))
			dt.Columns.Add(New DataColumn("Name", GetType(String)))
			dt.Columns.Add(New DataColumn("URL", GetType(String)))
			dt.Columns.Add(New DataColumn("UserImg", GetType(String)))
			dt.Columns.Add(New DataColumn("OnlineImg", GetType(String)))

			dt.Columns.Add(New DataColumn("Gender", GetType(String)))
			dt.Columns.Add(New DataColumn("MStatus", GetType(String)))
			dt.Columns.Add(New DataColumn("MeetPeopleFor", GetType(String)))
			dt.Columns.Add(New DataColumn("Age", GetType(Integer)))
			dt.Columns.Add(New DataColumn("Location", GetType(String)))
			dt.Columns.Add(New DataColumn("ProfileUpdated", GetType(String)))
			dt.Columns.Add(New DataColumn("NameFull", GetType(String)))

			' List search results
			Dim curUserUpdateDate As DateTime
			Dim age As TimeSpan
			Dim ageYears As Double

			If isGroupMode Then
				For Each result As GroupMember In invGroupUsers
					If counter >= startIndex AndAlso counter < endIndex Then
						dr = dt.NewRow()
						curUserUpdateDate = result.User.EditDate
						dr(0) = result.User.ID
						dr(1) = getBeginning(HttpUtility.HtmlEncode(result.User.Name), Constants.MAX_NAME_LENGTH_ABOVE_IMAGE)
						dr(11) = result.User.Name
						dr(2) = "../" + Constants.MEMBERS + "?id=" + result.User.ID
						pic = result.User.DefaultPicture
						If pic <> Nothing Then
							dr(3) = Pictures.GetPictureSrcFullURL(pic, True, "../")
						Else
							dr(3) = Constants.DEFAULT_THUMBNAIL_IMAGE_URL
						End If

						If LoggedUsersList.Contains(result.User.ID) Then
							dr(4) = "../images/online_status.gif"
						Else
							dr(4) = "../images/spacer.gif"
						End If

						If result.User.Gender > 0 Then
							dr(5) = Constants.ARR_GENDER(result.User.Gender)
						Else
							dr(5) = ""
						End If

						If result.User.MaritalStatus <> -1 Then
							dr(6) = Constants.ARR_STATUS(result.User.MaritalStatus)
						Else
							dr(6) = ""
						End If

						dr(7) = ""
						Dim tmp As String = ""
						If result.User.MatesSR Then
							tmp += "Serious Relationship, "
						End If
						If result.User.MatesPen Then
							tmp += "Penpals, "
						End If
						If result.User.MatesFriends Then
							tmp += "Friends, "
						End If
						If result.User.MatesDating Then
							tmp += "Dating, "
						End If
						If result.User.MatesAP Then
							tmp += "Activity Partners, "
						End If
						If result.User.MatesJHO Then
							tmp += "Just hanging out, "
						End If
						If tmp.Length > 0 Then
							tmp = tmp.Substring(0, tmp.LastIndexOf(","))
						End If
						dr(7) = tmp

						age = DateTime.Today - result.User.BirthDay
						ageYears = (age.Days / 365)
						dr(8) = ageYears

						dr(9) += result.User.City
						If result.User.City <> Nothing AndAlso result.User.City <> "" Then
							dr(9) += ", "
						End If
						If result.User.CountryID <> -1 Then
							dr(9) += Constants.COUNTRIES.GetCountryByID(result.User.CountryID).Name
						End If
						dr(10) = Constants.MONTHS(curUserUpdateDate.Month - 1) + " " + curUserUpdateDate.Day + ", " + curUserUpdateDate.Year + " " + curUserUpdateDate.ToShortTimeString()

						dt.Rows.Add(dr)
					End If
					System.Math.Max(System.Threading.Interlocked.Increment(counter),counter - 1)
				Next
			Else
				For Each result As DirectFriend In invUsers
					If counter >= startIndex AndAlso counter < endIndex Then
						dr = dt.NewRow()
						curUserUpdateDate = result.[Friend].EditDate
						dr(0) = result.[Friend].ID
						dr(1) = getBeginning(HttpUtility.HtmlEncode(result.[Friend].Name), Constants.MAX_NAME_LENGTH_ABOVE_IMAGE)
						dr(11) = result.[Friend].Name
						dr(2) = "../" + Constants.MEMBERS + "?id=" + result.[Friend].ID
						pic = result.[Friend].DefaultPicture
						If pic <> Nothing Then
							dr(3) = Pictures.GetPictureSrcFullURL(pic, True, "../")
						Else
							dr(3) = Constants.DEFAULT_THUMBNAIL_IMAGE_URL
						End If

						If LoggedUsersList.Contains(result.[Friend].ID) Then
							dr(4) = "../images/online_status.gif"
						Else
							dr(4) = "../images/spacer.gif"
						End If

						If result.[Friend].Gender > 0 Then
							dr(5) = Constants.ARR_GENDER(result.[Friend].Gender)
						Else
							dr(5) = ""
						End If

						If result.[Friend].MaritalStatus <> -1 Then
							dr(6) = Constants.ARR_STATUS(result.[Friend].MaritalStatus)
						Else
							dr(6) = ""
						End If

						dr(7) = ""
						Dim tmp As String = ""
						If result.[Friend].MatesSR Then
							tmp += "Serious Relationship, "
						End If
						If result.[Friend].MatesPen Then
							tmp += "Penpals, "
						End If
						If result.[Friend].MatesFriends Then
							tmp += "Friends, "
						End If
						If result.[Friend].MatesDating Then
							tmp += "Dating, "
						End If
						If result.[Friend].MatesAP Then
							tmp += "Activity Partners, "
						End If
						If result.[Friend].MatesJHO Then
							tmp += "Just hanging out, "
						End If
						If tmp.Length > 0 Then
							tmp = tmp.Substring(0, tmp.LastIndexOf(","))
						End If
						dr(7) = tmp

						age = DateTime.Today - result.[Friend].BirthDay
						ageYears = (age.Days / 365)
						dr(8) = ageYears

						dr(9) += result.[Friend].City
						If result.[Friend].City <> Nothing AndAlso result.[Friend].City <> "" Then
							dr(9) += ", "
						End If
						If result.[Friend].CountryID <> -1 Then
							dr(9) += Constants.COUNTRIES.GetCountryByID(result.[Friend].CountryID).Name
						End If
						dr(10) = Constants.MONTHS(curUserUpdateDate.Month - 1) + " " + curUserUpdateDate.Day + ", " + curUserUpdateDate.Year + " " + curUserUpdateDate.ToShortTimeString()

						dt.Rows.Add(dr)
					End If
					System.Math.Max(System.Threading.Interlocked.Increment(counter),counter - 1)
				Next
			End If
			Dim dv As New DataView(dt)
			Return dv
		End Function

		Protected Sub BindGrid()
			dgFavUsers.DataSource = CreateDataSource()
			dgFavUsers.PageSize = Constants.MAX_PICTURES_ON_AWAITING_PAGE
			dgFavUsers.DataBind()
		End Sub

		Private Sub dgFavUsers_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
			Dim usr As User = LoggedUser
			Dim cmd As String = e.CommandName
			Dim grp As Group = Groups.GetGroupByID(grpID)

			Select Case cmd
				Case "Accept"
					If isGroupMode Then
						grp.AcceptMembership(usr.ID, Convert.ToInt32(e.CommandArgument))
						Response.Redirect(Constants.VIEW_AWAITING_CONFIRMATION + "?" + Constants.GROUP_PARAM + "=" + grp.ID + "&" + Constants.CONFIRM_PARAM + "=" + Constants.ACCEPT_FRIENDSHIP)
					Else
						usr.AcceptCreateFriendship(Convert.ToInt32(e.CommandArgument))
						Response.Redirect(Constants.VIEW_AWAITING_CONFIRMATION + "?" + Constants.CONFIRM_PARAM + "=" + Constants.ACCEPT_FRIENDSHIP)
					End If
					Exit Select
				Case "Reject"
					If isGroupMode Then
						grp.RejectMembership(usr.ID, Convert.ToInt32(e.CommandArgument))
						Response.Redirect(Constants.VIEW_AWAITING_CONFIRMATION + "?" + Constants.GROUP_PARAM + "=" + grp.ID + "&" + Constants.CONFIRM_PARAM + "=" + Constants.REJECT_FRIENDSHIP)
					Else
						usr.RejectFriendship(Convert.ToInt32(e.CommandArgument))
						Response.Redirect(Constants.VIEW_AWAITING_CONFIRMATION + "?" + Constants.CONFIRM_PARAM + "=" + Constants.REJECT_FRIENDSHIP)
					End If
					Exit Select
				Case "MemberRedirect"
					Response.Redirect(Constants.MEMBERS + "?id=" + e.CommandArgument)
					Exit Select
			End Select
		End Sub
		Protected Overloads Overrides Sub Render(ByVal writer As HtmlTextWriter)
			Dim stringBuilder As New StringBuilder()
			Dim stringWriter As New StringWriter(stringBuilder)
			Dim htmlWriter As New HtmlTextWriter(stringWriter)
			MyBase.Render(htmlWriter)
			Dim html As String = stringBuilder.ToString()
			Dim start As Integer = html.IndexOf("<form name=""") + 12
			Dim [end] As Integer = html.IndexOf("""", start)
			Dim formID As String = html.Substring(start, [end] - start)
			Dim replace As String = formID.Replace(":", "_")
			html = html.Replace("document." + formID, "document." + replace)
			writer.Write(html)
		End Sub

		#region Web Form Designer generated code
		Protected Overloads Overrides Sub OnInit(ByVal e As EventArgs)
			'
			' CODEGEN: This call is required by the ASP.NET Web Form Designer.
			'
			InitializeComponent()
			MyBase.OnInit(e)
		End Sub

		''' <summary>
		''' Required method for Designer support - do not modify
		''' the contents of this method with the code editor.
		''' </summary>
		Private Sub InitializeComponent()
			AddHandler Me.dgFavUsers.ItemCommand, AddressOf Me.dgFavUsers_ItemCommand
		End Sub
#End Region

		====================
		' This public property was added by conversion wizard to allow the access of a protected, autogenerated member variable _Form1.
		====================
		Public ReadOnly Property _Form1() As System.Web.UI.HtmlControls.HtmlForm
			Get
				Return Migrated__Form1
			End Get
		End Property
		'set { Migrated__Form1 = value; }
	End Class
End Namespace






